<template>
  <div>
    <form class="card comment-form">
      <div class="card-block">
        <textarea
          class="form-control"
          placeholder="Write a comment..."
          rows="3"
          v-model="comment"
        ></textarea>
      </div>
      <div class="card-footer">
        <img
          :src="
            user
              ? user.image
              : 'https://static.productionready.io/images/smiley-cyrus.jpg'
          "
          class="comment-author-img"
        />
        <button class="btn btn-sm btn-primary" @click.prevent="addComments">
          Post Comment
        </button>
      </div>
    </form>
    <template v-for="ele in comments">
      <div class="card" :key="ele.id">
        <div class="card-block">
          <p class="card-text">
            {{ ele.body }}
          </p>
        </div>
        <div class="card-footer">
          <nuxt-link
            :to="{
              name: 'Profile',
              params: {
                username: ele.author.username
              }
            }"
            class="comment-author"
          >
            <img :src="ele.author.image" class="comment-author-img" />
          </nuxt-link>
          &nbsp;
          <nuxt-link
            :to="{
              name: 'Profile',
              params: {
                username: ele.author.username
              }
            }"
            class="comment-author"
          >
            {{ ele.author.username }}
          </nuxt-link>
          <span class="date-posted">{{
            ele.createdAt | date('MMM DD, YYYY')
          }}</span>
        </div>
      </div>
    </template>
  </div>
</template>

<script>
/*eslint-disable */
import { mapState } from 'vuex'
import { getComments, addComments } from '../../api/index'
export default {
  data() {
    return {
      comments: [],
      comment: ''
    }
  },
  created() {
    console.log(this.user)
  },
  computed: {
    ...mapState(['user'])
  },
  props: ['slug'],
  async created() {
    await this.getComments()
  },
  methods: {
    async getComments() {
      const res = await getComments(this.slug)
      console.log(res)
      this.comments = res.data.comments
    },
    async addComments() {
      if (!this.comment) {
        return
      }
      try {
        const res = await addComments(this.slug, {
          body: this.comment
        })
        console.log(res)
        await this.getComments()
        this.$message.info('评论成功')
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>

<style scoped></style>
